<?php

namespace App\Repositories;

use App\Interfaces\BrandService;
use App\Models\Brand;
use App\Models\Category;
use App\Models\CategoryBrand;

class BrandRepository implements BrandService
{

    protected $brand;

    public function __construction(Brand $brand)
    {
        $this->brand = $brand;
    }

    /**
     * 根据ID获取品牌
     * @param $id
     * @return mixed
     */
    public function get($id)
    {
        return Brand::find($id);
    }

    public function getBrandByIds(Array $brand_ids){
        return Brand::whereIn('brand_id',$brand_ids)->get();
    }

    /**
     * 获取推荐品牌
     * @return mixed
     */
    public function getIndexRecommend()
    {
        $recommendBrand = Brand::where('is_recommend', 1)->orderBy('sort_order', 'desc')->get()->take(12);
        return $recommendBrand;
    }

    public function getCatBrands($cat_id){

        $categoryBrandIds = CategoryBrand::where('cat_id',$cat_id)->lists('brand_id')->toArray();
        $brands = Brand::whereIn('brand_id',$categoryBrandIds)
            ->orderBy('sort_order','desc')
            ->get();
        return $brands;

    }

    /**
     * 获取分类下所有推荐品牌
     * add by shenchangwei
     * @param $cat_id
     * @return mixed
     */
    public function getCatRecommendBrands($cat_id)
    {

        $category = Category::find($cat_id);
        if($category){
            $categoryIdArr = $category->getChildIds();
            $brands = Brand::select('brand.*','category_brand.cat_id')
                ->join('category_brand','category_brand.brand_id','=','brand.brand_id')
                ->whereIn('category_brand.cat_id',$categoryIdArr)
                ->where('category_brand.is_recommend',0)
                ->orderBy('brand.sort_order','desc')
                ->groupBy('brand.brand_id')
                ->get()->take(12);
            //dd($brands);
            return $brands;
        }else{
            return collection();
        }


    }

}